


set export

applyTemplate DIALECT_NAME DIALECT_NS PROJECT_PREFIX OUT_DIR:
    #!/bin/bash

    TMPDIR=$(mktemp -d)
    cp -r ./templateFiles/* "$TMPDIR"
    pushd "$TMPDIR"

    declare -A vardict
    vardict["dialectNameUpper"]=$DIALECT_NAME
    vardict["dialectNameAllCaps"]=${DIALECT_NS^^}
    vardict["dialectNs"]=$DIALECT_NS
    vardict["projectPrefix"]=$PROJECT_PREFIX

    # rename files and directories
    for varname in "${!vardict[@]}"; do
        find . -depth -exec bash -c 'REPLACED="${1//\$\{$2\}/$3}"; if [[ $REPLACED != $1 ]]; then mkdir -p $(dirname $REPLACED); mv $1 $REPLACED; fi' - '{}' "$varname" "${vardict[$varname]}" \;
    done
    # remove empty dirs
    find . -depth -empty -delete

    # replace within files
    for varname in "${!vardict[@]}"; do
        find . -type f -exec bash -c 'sed -i "s/\${$2}/$3/g" $1' - '{}' "$varname" "${vardict[$varname]}" \;
    done

    find . -type f -exec bash -c  'if [[ -e "$2/$1" ]]; then cat "$1" >> "$2/$1"; else mkdir -p $(dirname "$2/$1"); cp "$1" "$2/$1"; fi' - '{}' "$OUT_DIR"  \;

    popd

    echo "Done. Check changes for correctness!"
